// https://leetcode.cn/problems/search-a-2d-matrix/description/?envType=study-plan-v2&envId=top-interview-150

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int m = matrix.size(), n = matrix[0].size();
        int left = 0, right = m * n - 1;

        while (left <= right) {
            int mid = (right - left) / 2 + left;
            int x = mid / n, y = mid % n;

            if (matrix[x][y] < target) {
                left = mid + 1;
            } else if (matrix[x][y] > target) {
                right = mid - 1;
            } else {
                return true;
            }
        }
        return false;
    }
};